/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.hauntedhousesweb.web;

import cz.muni.fi.hauntedhouses.service.AuthoritiesService;
import cz.muni.fi.hauntedhouses.service.UsersService;
import cz.muni.fi.hauntedhouses.to.AuthoritiesTO;
import cz.muni.fi.hauntedhouses.to.HumanTO;
import cz.muni.fi.hauntedhouses.to.UsersTO;
import java.beans.*;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;

/**
 *
 * @author Jan Volmut, 324836
 */
@UrlBinding("/registration/{$event}")
public class RegistrationActionBean implements ActionBean {
    
    private ActionBeanContext context;
    
    @SpringBean
    private UsersService usersService;
    
    @SpringBean
    private AuthoritiesService authoritiesService;
    
    @ValidateNestedProperties(value = {
    @Validate(on = {"add"}, field = "username", required = true),
    @Validate(on = {"add"}, field = "password", required = true)
    })
    private UsersTO users;
    
    @Override
    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    @Override
    public ActionBeanContext getContext() {
        return context;
    }

    public UsersTO getUsers() {
        return users;
    }

    public void setUsers(UsersTO users) {
        this.users = users;
    }
    
    @DefaultHandler
    public Resolution all() {
        return new ForwardResolution("/registration.jsp");
    }
    
    public Resolution add() {
        users.setEnabled(Boolean.TRUE);
        usersService.create(users);
        AuthoritiesTO role = new AuthoritiesTO();
        role.setAuthority("ROLE_USER");
        role.setUsername(users.getUsername());
        authoritiesService.create(role);
        return new RedirectResolution("/index.jsp");
    }
}
